﻿using ProductSystem.BLL;
using ProductSystem.BLL.Common;
using ProductSystem.Model;
using Fundway.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace ProductSystem.Web.Controllers
{
    public class SystemController : ManageControllerBase
    {
        #region 用户管理
        /// <summary>
        /// 用户管理
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-UserList")]
        public ActionResult UserList(string User)
        {
            PageInfo pageInfo = GetPageInfo();
            List<System_User_Info> list = System_User_InfoBll.GetList(User, ref pageInfo);
            ViewData["UserRoleList"] = V_User_RoleBll.GetList();
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            ViewData["User"] = User;
            return View();
        }

        /// <summary>
        /// 用户添加
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-UserList")]
        public ActionResult UserAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加用户保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-UserList")]
        public ActionResult UserAdd(System_User_Info model)
        {
            try
            {
                string roleId = Request["hidUserRole"];
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    if (System_User_InfoBll.ExitAccount(model.Account, 0))
                    {
                        return Json(PromptMessage.Instance().GetPrompt(false, "已有该用户信息！"), JsonRequestBehavior.AllowGet);
                    }
                    model.Status = 1;
                    model.Create_Date = DateTime.Now;
                    model.Password = EncryptManager.EncryptTokenForPassword(model.Password);
                    Telerik.OpenAccess.ConcurrencyConflictsProcessingMode m = new Telerik.OpenAccess.ConcurrencyConflictsProcessingMode();
                    dbContext.Add(model);
                    dbContext.SaveChanges(m);
                    if (!string.IsNullOrEmpty(roleId))
                    {
                        string[] ids = roleId.Split(',');
                        for (int i = 0; i < ids.Count(); i++)
                        {
                            System_User_Role su = new System_User_Role();
                            su.Role_ID = Convert.ToInt32(ids[i]);
                            su.User_ID = model.ID;
                            dbContext.Add(su);
                        }
                        dbContext.SaveChanges();
                    }
                }
                return Json(PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptAddSuccess), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptAddFail), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 编辑用户显示
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-UserList")]
        public ActionResult UserEdit(int id)
        {
            string roleId = string.Empty;
            string roleName = string.Empty;
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                List<V_User_ROle> list = dbContext.V_User_ROles.Where(m => m.User_ID == id).ToList();
                foreach (V_User_ROle m in list)
                {
                    if (string.IsNullOrEmpty(roleId))
                    {
                        roleId = m.Role_ID.ToString();
                        roleName = m.Role_Name;
                    }
                    else
                    {
                        roleId += "," + m.Role_ID.ToString();
                        roleName += "," + m.Role_Name;
                    }
                }
                System_User_Info model = dbContext.System_User_Infos.FirstOrDefault(m => m.ID == id);
                ViewData.Model = model;
                ViewData["roleId"] = roleId;
                ViewData["roleName"] = roleName;
            }
            return View();
        }

        /// <summary>
        /// 编辑用户保存
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="collection">用户实体</param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-UserList")]
        public ActionResult UserEdit(int id, System_User_Info model)
        {
            try
            {
                string oldroleId = Request["oldUserRole"];
                string roleId = Request["hidUserRole"];
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    System_User_Info m = dbContext.System_User_Infos.FirstOrDefault(t => t.ID == id);
                    m.Mobile = model.Mobile;
                    m.Email = model.Email;
                    m.Status = m.Status;
                    m.User_Name = model.User_Name;
                    m.Account = model.Account;
                    if (System_User_InfoBll.ExitAccount(m.Account, id))
                    {
                        return Json(PromptMessage.Instance().GetPrompt(false, "该账号已存在！"), JsonRequestBehavior.AllowGet);
                    }
                    if (!string.IsNullOrEmpty(model.Password))
                    {
                        m.Password = EncryptManager.EncryptTokenForPassword(model.Password);
                    }
                    m.Revised_Date = DateTime.Now;
                    dbContext.SaveChanges();
                    if (!string.IsNullOrEmpty(roleId) && roleId != oldroleId)
                    {
                        //删除用户角色
                        string sql = "delete System_User_Roles WHERE User_ID=" + id;
                        dbContext.ExecuteNonQuery(sql);
                        //添加用户角色
                        string[] ids = roleId.Split(',');
                        for (int i = 0; i < ids.Count(); i++)
                        {
                            System_User_Role su = new System_User_Role();
                            su.Role_ID = Convert.ToInt32(ids[i]);
                            su.User_ID = model.ID;
                            dbContext.Add(su);
                        }
                        dbContext.SaveChanges();
                    }
                }
                return Json(PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 角色Json
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUserRoleJson()
        {
            List<System_Role> lsit = System_RoleBll.GetList();
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (System_Role model in lsit)
            {
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", model.ID);
                sb.AppendFormat("\"pId\":\"0\",");
                sb.AppendFormat("\"name\":\"{0}\"", model.Role_Name);
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            return Content(sb.ToString());
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ids">角色ID</param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-UserList")]
        public ActionResult DelUser(String ids)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Count(); i++)
                    {
                        System_User_Info m = dbContext.System_User_Infos.FirstOrDefault(t => t.ID == Convert.ToInt32(idList[i]));
                        m.Status = 0;
                        TryUpdateModel(m);
                    }
                    dbContext.SaveChanges();
                }
                rs.Status = true;
                rs.ErrorCode = 1;
                rs.ErrorMessage = "删除成功";
            }
            catch
            {
                rs.Status = false;
                rs.ErrorCode = 0;
                rs.ErrorMessage = "删除异常";
            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 判断用户账号是否存在
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true)]
        public JsonResult ValidateUserAccount(string userAccount, int id = 0)
        {
            bool isSuccess = true;
            string messageContent = string.Empty;
            if (System_User_InfoBll.ExitAccount(userAccount, id))
            {
                isSuccess = false;
                messageContent = "账号已存在";
            }
            return Json(new { isSuccess = isSuccess, messageContent = messageContent }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 编辑当前登录用户的信息(界面显示)
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        [ManageAuthorize]
        public ActionResult LoginUserInfoEdit(int id)
        {
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                System_User_Info model = dbContext.System_User_Infos.FirstOrDefault(m => m.ID == id);
                ViewData.Model = model;
            }
            return View();
        }

        /// <summary>
        /// 编辑当前登录用户的信息(数据保存)
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="model">用户实体类</param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize]
        public ActionResult LoginUserInfoEdit(int id, System_User_Info model)
        {
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    System_User_Info m = dbContext.System_User_Infos.FirstOrDefault(t => t.ID == id);
                    m.User_Name = model.User_Name;
                    m.Mobile = model.Mobile;
                    m.Email = model.Email;
                    m.Status = m.Status;
                    string oldPassWord = Request.Params["oldPassword"];
                    if (!string.IsNullOrEmpty(oldPassWord))
                    {
                        if (EncryptManager.EncryptTokenForPassword(oldPassWord) == m.Password)
                        {
                            if (!string.IsNullOrEmpty(model.Password))
                            {
                                m.Password = EncryptManager.EncryptTokenForPassword(model.Password);
                            }
                        }
                        else
                        {
                            return Content("w");
                        }
                    }
                    m.Revised_Date = DateTime.Now;
                    dbContext.SaveChanges();
                }
                return Content("y");
            }
            catch
            {
                return Content("n");
            }
        }
        #endregion
        #region 角色管理
        /// <summary>
        /// 角色管理
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-RoleList")]
        public ActionResult RoleList(string Role)
        {
            PageInfo pageInfo = GetPageInfo();
            List<System_Role> list = System_RoleBll.GetList(Role, ref pageInfo);
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            ViewData["Role"] = Role;
            return View();
        }

        /// <summary>
        /// 添加角色显示
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-RoleList")]
        public ActionResult RoleAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加角色保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-RoleList")]
        public ActionResult RoleAdd(System_Role model)
        {
            model.Status = 1;
            DataAddGeneric<System_Role>.isExist = System_RoleBll.IsExist;
            ReturnStatus rs = DataAddGeneric<System_Role>.Add(model);
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 编辑角色显示
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-RoleList")]
        public ActionResult RoleEdit(int id)
        {
            ViewData.Model = System_RoleBll.GetData(id);
            return View();
        }

        /// <summary>
        /// 编辑角色保存
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <param name="collection">角色实体</param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-RoleList")]
        public ActionResult RoleEdit(int id, FormCollection collection)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    System_Role model = dbContext.System_Roles.FirstOrDefault(o => o.ID == id);
                    if (TryUpdateModel(model))
                    {
                        if (!System_RoleBll.IsExist(model))
                        {
                            dbContext.SaveChanges();
                            rs = PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess);
                        }
                        else
                        {
                            rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditExist);
                        }
                    }
                    else
                    {
                        rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);
                    }
                }
            }
            catch
            {
                rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);
            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ids">角色ID</param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-RoleList")]
        public ActionResult DelRole(String ids)
        {
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Count(); i++)
                    {
                        System_Role m = dbContext.System_Roles.FirstOrDefault(t => t.ID == Convert.ToInt32(idList[i]));
                        m.Status = 0;

                        var menuRoleList = dbContext.System_Menu_Roles.Where(o => o.Role_ID == Convert.ToInt32(idList[i]));
                        dbContext.Delete(menuRoleList);

                        var userRoleList = dbContext.System_User_Roles.Where(o => o.Role_ID == Convert.ToInt32(idList[i]));
                        dbContext.Delete(userRoleList);
                    }
                    dbContext.SaveChanges();
                }
                return Json(PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptDeleteSuccess), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptDeleteFail), JsonRequestBehavior.AllowGet);
            }
        }
        #endregion
        #region 权限管理
        /// <summary>
        /// 角色管理列表
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-PowerList")]
        public ActionResult PowerList(string Role)
        {
            PageInfo pageInfo = GetPageInfo();
            List<System_Role> list = System_RoleBll.GetList(Role, ref pageInfo);
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            return View();
        }

        /// <summary>
        /// 权限设置
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-PowerList")]
        public ActionResult PowerManage(int roleId)
        {
            List<System_Menu_Role> list = System_Menu_RoleBll.GetAllList(roleId);
            string ids = string.Empty;
            foreach (System_Menu_Role m in list)
            {
                ids = ids + m.Menu_ID.ToString() + ",";
            }
            if (ids.ToString().EndsWith(","))
            {
                ids = ids.Remove(ids.Length - 1, 1);
            }
            ViewData["roleId"] = roleId;
            ViewData["ids"] = ids;
            return View();
        }

        /// <summary>
        /// 角色权限保存
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="roledList">菜单IDs</param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-PowerList")]
        public ActionResult PowerManageSave(int roleId, string roledList)
        {
            string[] idlist = roledList.Split(',');
            try
            {
                // TODO: Add insert logic here
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    if (idlist.Length > 0)
                    {
                        string sql = "delete System_Menu_Role where Role_ID=" + roleId;
                        dbContext.ExecuteNonQuery(sql);
                    }
                    for (int i = 0; i < idlist.Length; i++)
                    {
                        System_Menu_Role model = new System_Menu_Role();
                        model.Menu_ID = Convert.ToInt32(idlist[i]);
                        model.Role_ID = roleId;
                        dbContext.Add(model);
                    }
                    dbContext.SaveChanges();
                }
                return Content("y");
            }
            catch
            {
                return Content("n");
            }
        }

        /// <summary>
        /// 权限编辑
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        public ActionResult GetMenuTreeJson(int roleId)
        {
            List<System_Menu> menulist = System_MenuBll.GetList(-1);
            string str = System_MenuBll.GetMenuTreeJson(0, menulist, 1);
            return Content(str);
        }
        #endregion
        #region 菜单管理
        /// <summary>
        /// 菜单管理
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult MenuList()
        {
            return View();
        }

        /// <summary>
        /// 权限Json
        /// </summary>
        /// <param name="menuId">菜单ID</param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult GetSystemTreeJson(int menuId)
        {
            List<System_Menu> SystemFunctionlist = System_MenuBll.GetList(-1);
            string str = System_MenuBll.GetMenuTreeJson(menuId, SystemFunctionlist);
            return Content(str.Substring(12));
        }

        /// <summary>
        /// 菜单添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult MenuAdd()
        {
            List<System_Menu> list = System_MenuBll.GetList(-1);
            ViewBag.MenuList = list;
            return View();
        }

        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult MenuAdd(System_Menu model)
        {
            try
            {
                // TODO: Add insert logic here
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    model.Status = 1;
                    Telerik.OpenAccess.ConcurrencyConflictsProcessingMode m = new Telerik.OpenAccess.ConcurrencyConflictsProcessingMode();
                    dbContext.Add(model);
                    dbContext.SaveChanges(m);
                }
                return Content("y");
            }
            catch
            {
                return Content("n");
            }
        }

        /// <summary>
        /// 系统功能编辑
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult MenuEdit(int id)
        {
            List<System_Menu> list = System_MenuBll.GetList(-1);
            ViewBag.MenuList = list;
            if (id > 0)
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    System_Menu model = dbContext.System_Menus.FirstOrDefault(m => m.ID == id);
                    ViewData.Model = model;
                    System_Menu sm = list.FirstOrDefault(m => m.ID == model.Parent_ID);
                    if (sm != null)
                        ViewData["parentName"] = sm.Menu_Name;
                }
            }
            return View();
        }

        /// <summary>
        /// 系统功能编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult MenuEdit(System_Menu model)
        {
            try
            {
                // TODO: Add update logic here
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    System_Menu m = dbContext.System_Menus.FirstOrDefault(t => t.ID == model.ID);
                    m.Is_Menu = model.Is_Menu;
                    m.Menu_Action = model.Menu_Action;
                    m.Menu_Controller = model.Menu_Controller;
                    m.Menu_Name = model.Menu_Name;
                    m.Menu_Order = model.Menu_Order;
                    m.Menu_Type = model.Menu_Type;
                    m.Page_Url = model.Page_Url;
                    m.Parent_ID = model.Parent_ID;
                    m.Pictures_Name = model.Pictures_Name;
                    m.Remark = model.Remark;
                    dbContext.SaveChanges();
                }
                return Content("y");
            }
            catch
            {
                return Content("n");
            }
        }

        /// <summary>
        /// 删除功能菜单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-MenuList")]
        public ActionResult DelMenu(String ids)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                // TODO: del update logic here
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Count(); i++)
                    {
                        System_Menu m = dbContext.System_Menus.FirstOrDefault(t => t.ID == Convert.ToInt32(idList[i]));
                        m.Status = 0;
                        TryUpdateModel(m);
                    }
                    dbContext.SaveChanges();
                }
                rs.Status = true;
                rs.ErrorCode = 1;
                rs.ErrorMessage = "删除成功";
            }
            catch
            {
                rs.Status = false;
                rs.ErrorCode = 0;
                rs.ErrorMessage = "删除异常";
            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 日志管理
        /// <summary>
        /// 日志列表显示
        /// </summary>
        /// <param name="userAccount"></param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-SysLogList")]
        public ActionResult SysLogList(string userAccount)
        {
            int pagesize;      //每页行数
            if (Request.Cookies["PageSize"] != null)    //cookie如果不为空，将读取cookie作为pageSize的值
                pagesize = Int32.Parse(Request.Cookies["PageSize"].Value);
            else
                pagesize = Request.QueryString.GetInt("pageSize", 10);
            int curpage = Request.QueryString.GetInt("page", 1);//当前页
            if (Request["pageIndex"] != null)
            {
                curpage = int.Parse(Request["pageIndex"]);
            }
            int recordCount = 0;
            List<System_Log_User> list = System_Log_UserBll.GetList(userAccount, curpage, pagesize, ref recordCount);
            ViewData.Model = list;
            ViewBag.PageSize = pagesize;
            ViewBag.CurrentPage = curpage;
            ViewBag.TotalCount = recordCount;
            ViewData["UserAccount"] = userAccount;
            return View();
        }

        /// <summary>
        /// 删除日志操作
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-SysLogList")]
        public ActionResult DelSysLog(String ids)
        {
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                List<string> idList = ids.Split(',').ToList();
                var list = dbContext.System_Log_Users.Where(o => idList.Contains(o.Id.ToString())).ToList();
                ReturnStatus rs = System_Log_UserBll.DeleteSysLog(ids);
                return Json(rs, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion
        #region 类型码管理
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-TypeList")]
        public ActionResult TypeList(string CodeType)
        {
            int pagesize;      //每页行数
            if (Request.Cookies["PageSize"] != null)    //cookie如果不为空，将读取cookie作为pageSize的值
            {
                pagesize = Int32.Parse(Request.Cookies["PageSize"].Value);
            }
            else
            {
                pagesize = Request.QueryString.GetInt("pageSize", 10);
            }
            int curpage = Request.QueryString.GetInt("page", 1);//当前页
            if (Request["pageIndex"] != null)
            {
                curpage = int.Parse(Request["pageIndex"]);
            }
            int recordCount = 0;

            List<Code_Type> list = Code_TypeBll.GetList(CodeType, curpage, pagesize, ref recordCount);
            ViewData.Model = list;
            ViewBag.PageSize = pagesize;
            ViewBag.CurrentPage = curpage;
            ViewBag.TotalCount = recordCount;
            ViewData["CodeType"] = CodeType;
            return View();
        }

        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-TypeList")]
        public ActionResult TypeAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加CodeType保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-TypeList")]
        public ActionResult TypeAdd(Code_Type model)
        {
            model.Status = 1;
            DataAddGeneric<Code_Type>.isExist = Code_TypeBll.IsExist;
            ReturnStatus rs = DataAddGeneric<Code_Type>.Add(model);
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-TypeList")]
        public ActionResult TypeEdit(int id)
        {
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                Code_Type model = dbContext.Code_Types.FirstOrDefault(m => m.ID == id);
                ViewData.Model = model;
            }
            return View();
        }

        /// <summary>
        /// 修改Code_Type保存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-TypeList")]
        public ActionResult TypeEdit(int id, FormCollection collection)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    Code_Type model = dbContext.Code_Types.FirstOrDefault(o => o.ID == id);
                    if (TryUpdateModel(model))
                    {
                        if (Code_TypeBll.IsExist(model))
                        {
                            return Json(PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditExist), JsonRequestBehavior.AllowGet);
                        }
                        dbContext.SaveChanges();
                    }
                }
                rs = PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess);
            }
            catch
            {
                rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);

            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-TypeList")]
        public ActionResult DelCodeType(String ids)
        {
            ReturnStatus rs = new ReturnStatus();
            if (Code_TypeBll.DeleteTypeCode(ids))
            {
                rs.Status = true;
                rs.ErrorCode = 1;
                rs.ErrorMessage = "删除成功";
            }
            else
            {
                rs.Status = false;
                rs.ErrorCode = 0;
                rs.ErrorMessage = "删除异常";
            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 基础码管理
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-CodeList")]
        public ActionResult CodeList(string BaseCode)
        {
            PageInfo pageInfo = GetPageInfo();
            List<Base_Code> list = Base_CodeBll.GetList(BaseCode, pageInfo);
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            ViewData["BaseCode"] = BaseCode;
            return View();
        }

        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-CodeList")]
        public ActionResult CodeAdd()
        {
            List<Code_Type> list = Code_TypeBll.GetAllList(1);
            ViewData.Model = list;
            return View();
        }

        /// <summary>
        /// 添加CodeType保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-CodeList")]
        public ActionResult CodeAdd(Base_Code model)
        {
            model.Status = 1;
            DataAddGeneric<Base_Code>.isExist = Base_CodeBll.IsExist;
            ReturnStatus rs = DataAddGeneric<Base_Code>.Add(model);
            Base_CodeBll.Cache();
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 码类型Json
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTypeCodeJson()
        {
            List<Code_Type> lsit = Code_TypeBll.GetAllList(1);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (Code_Type model in lsit)
            {
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", model.Type_Code);
                sb.AppendFormat("\"pId\":\"0\",");
                sb.AppendFormat("\"name\":\"{0}\"", model.Type_Name);
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            return Content(sb.ToString());
        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-CodeList")]
        public ActionResult DelBaseCode(String ids)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                // TODO: del update logic here
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Count(); i++)
                    {
                        Base_Code m = dbContext.Base_Codes.FirstOrDefault(t => t.ID == Convert.ToInt32(idList[i]));
                        m.Status = 0;
                        TryUpdateModel(m);
                    }
                    dbContext.SaveChanges();
                }
                rs.Status = true;
                rs.ErrorCode = 1;
                rs.ErrorMessage = "删除成功";
            }
            catch
            {
                rs.Status = false;
                rs.ErrorCode = 0;
                rs.ErrorMessage = "删除异常";
            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-CodeList")]
        public ActionResult CodeEdit(int id)
        {
            Base_Code data = Base_CodeBll.GetData(id);
            ViewData.Model = data;
            return View();
        }

        /// <summary>
        /// 修改Code_Type保存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-CodeList")]
        public ActionResult CodeEdit(int id, FormCollection collection)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    Base_Code model = dbContext.Base_Codes.FirstOrDefault(o => o.ID == id);
                    if (TryUpdateModel(model))
                    {
                        if (Base_CodeBll.IsExist(model))
                        {
                            return Json(PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditExist), JsonRequestBehavior.AllowGet);
                        }
                        dbContext.SaveChanges();
                        Base_CodeBll.Cache();
                    }
                }
                rs = PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess);
            }
            catch
            {
                rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);

            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 餐桌管理
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-DeskList")]
        public ActionResult DeskList(string deskNumber)
        {
            PageInfo pageInfo = GetPageInfo();
            List<Desk> list = Desk_Bll.GetList(deskNumber, ref pageInfo);
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            ViewData["DeskNumber"] = deskNumber;
            return View();
        }

        /// <summary>
        /// 餐桌添加
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-DeskList")]
        public ActionResult DeskAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加餐桌保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-DeskList")]
        public ActionResult DeskAdd(Desk model)
        {
            model.DeskTypeId = 1; //空闲
            model.Status = 1;
            //DataAddGeneric<Desk>.isExist = Desk_Bll.IsExist;
            ReturnStatus rs = DataAddGeneric<Desk>.Add(model);
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-DeskList")]
        public ActionResult DeskEdit(int id)
        {
            Desk desk = Desk_Bll.GetData(id);
            ViewData.Model = desk;
            return View();
        }

        /// <summary>
        /// 修改餐桌保存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-DeskList")]
        public ActionResult DeskEdit(int id, FormCollection collection)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    Desk model = dbContext.Desks.FirstOrDefault(o => o.ID == id);
                    if (TryUpdateModel(model))
                    {
                        //if (Desk_Bll.IsExist(model))
                        //{
                        //    return Json(PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditExist), JsonRequestBehavior.AllowGet);
                        //}
                        dbContext.SaveChanges();
                    }
                }
                rs = PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess);
            }
            catch
            {
                rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);

            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除餐桌
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-DeskList")]
        public ActionResult DelDesk(String ids)
        {
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                List<string> idList = ids.Split(',').ToList();
                var list = dbContext.Desks.Where(o => idList.Contains(o.ID.ToString())).ToList();
                ReturnStatus rs = Desk_Bll.DeleteDesk(ids);
                return Json(rs, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion
        #region 菜分类
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodTypeList")]
        public ActionResult FoodTypeList()
        {
            PageInfo pageInfo = GetPageInfo();
            List<FoodType> list = FoodType_Bll.GetList(ref pageInfo);
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            return View();
        }

        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodTypeList")]
        public ActionResult FoodTypeAdd()
        {
            return View();
        }

        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodTypeList")]
        public ActionResult FoodTypeAdd(FoodType model)
        {
            //DataAddGeneric<Desk>.isExist =Desk_Bll.IsExist;
            ReturnStatus rs = DataAddGeneric<FoodType>.Add(model);
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodTypeList")]
        public ActionResult FoodTypeEdit(int id)
        {
            FoodType foodType = FoodType_Bll.GetData(id);
            ViewData.Model = foodType;
            return View();
        }

        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodTypeList")]
        public ActionResult FoodTypeEdit(int id, FormCollection collection)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    FoodType model = dbContext.FoodTypes.FirstOrDefault(o => o.ID == id);
                    if (TryUpdateModel(model))
                    {
                        dbContext.SaveChanges();
                    }
                }
                rs = PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess);
            }
            catch
            {
                rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);

            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodTypeList")]
        public ActionResult DelFoodType(String ids)
        {
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                List<string> idList = ids.Split(',').ToList();
                var list = dbContext.FoodTypes.Where(o => idList.Contains(o.ID.ToString())).ToList();
                ReturnStatus rs = FoodType_Bll.DeleteFoodType(ids);
                return Json(rs, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion
        #region 菜
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodList")]
        public ActionResult FoodList()
        {
            PageInfo pageInfo = GetPageInfo();
            List<Food> list = Food_Bll.GetList(ref pageInfo);
            ViewData.Model = list;
            ViewBag.PageSize = pageInfo.PageSize;
            ViewBag.CurrentPage = pageInfo.CurPage;
            ViewBag.TotalCount = pageInfo.TotalCount;
            return View();
        }

        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodList")]
        public ActionResult FoodAdd()
        {
            return View();
        }

        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodList")]
        public ActionResult FoodAdd(Food model)
        {
            model.Status = 1;
            //DataAddGeneric<Desk>.isExist =Desk_Bll.IsExist;
            ReturnStatus rs = DataAddGeneric<Food>.Add(model);
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodList")]
        public ActionResult FoodEdit(int id)
        {
            Food food = Food_Bll.GetData(id);
            ViewData.Model = food;
            return View();
        }

        [HttpPost]
        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodList")]
        public ActionResult FoodEdit(int id, FormCollection collection)
        {
            ReturnStatus rs = new ReturnStatus();
            try
            {
                using (EntitiesModel dbContext = new EntitiesModel())
                {
                    Food model = dbContext.Food.FirstOrDefault(o => o.ID == id);
                    if (TryUpdateModel(model))
                    {
                        dbContext.SaveChanges();
                    }
                }
                rs = PromptMessage.Instance().GetPrompt(true, TBConfig.Instance().GetPromptEditSuccess);
            }
            catch
            {
                rs = PromptMessage.Instance().GetPrompt(false, TBConfig.Instance().GetPromptEditFail);

            }
            return Json(rs, JsonRequestBehavior.AllowGet);
        }

        [ManageAuthorize(RequireCheckRole = true, ActionName = "System-FoodList")]
        public ActionResult DelFood(String ids)
        {
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                List<string> idList = ids.Split(',').ToList();
                var list = dbContext.Food.Where(o => idList.Contains(o.ID.ToString())).ToList();
                ReturnStatus rs = FoodType_Bll.DeleteFoodType(ids);
                return Json(rs, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion
    }
}
